package com.example.hao.greendao.activity;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

import com.example.hao.greendao.R;
import com.example.hao.greendao.pojo.Student;

import com.example.hao.greendao.pojo.StudentDao;
import com.example.hao.greendao.utils.DBUtils;
import com.orhanobut.logger.Logger;

import org.greenrobot.greendao.query.WhereCondition;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.btn_insert)
    Button btnInsert;
    @BindView(R.id.btn_delete)
    Button btnDelete;
    @BindView(R.id.btn_update)
    Button btnUpdate;
    @BindView(R.id.btn_query)
    Button btnQuery;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);


    }

    @OnClick({R.id.btn_insert, R.id.btn_delete, R.id.btn_update, R.id.btn_query})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_insert:
                insertStudent();
                break;
            case R.id.btn_delete:
                deleteStudent();
                break;
            case R.id.btn_update:
                updateStudent();
                break;
            case R.id.btn_query:
                queryStudent();
                break;
        }
    }

    private void queryStudent() {
//        List<Student> students = DBUtils.getSession().getStudentDao().loadAll();
        List<Student> students = DBUtils.getSession().getStudentDao().queryBuilder()
                .whereOr(StudentDao.Properties.Id.le(4), StudentDao.Properties.Id.gt(7))
                .build().list();

        for (Student stu : students) {
            Logger.w("student: %s", stu);
        }
    }


    private void insertStudent() {
        long insert = DBUtils.getSession().getStudentDao().insert(new Student("张三", 18));
        Logger.d("id: %s", insert);

    }

    private void deleteStudent() {
        DBUtils.getSession().getStudentDao().deleteByKey(4L);
        Logger.i("删除成功");
    }

    private void updateStudent() {
        Student load = DBUtils.getSession().getStudentDao().load(2L);
        Logger.w(load.toString());
        load.setName("李四");//修改数据
        DBUtils.getSession().getStudentDao().update(load);//将修改的数据,写入到数据库表中
    }


}
